package exteditapp.state;

import exteditapp.AppStarter;
import exteditapp.AppletIterator;
import exteditapp.FileDefault;
import exteditapp.action.ActionDownloading;
import exteditapp.command.CommandDownload;

/**
 * State - file download process
 * @author Arturas Smorgun, arturas@smorgun.lt
 */
public class StateDownloading extends IState {

	/**
	 * Default constructor
	 * @param iterator is system iterator, which performs all actions
	 * @param file this is file, which state we will hold
	 */
	public StateDownloading(AppletIterator iterator, FileDefault file) {
		super(iterator, file);
		start();
	}
	public StateDownloading(AppletIterator iterator, FileDefault file, boolean doRegister){
		super(iterator, file, doRegister);
		start();
	}
	
	protected void start(){
		this.setAction(new ActionDownloading());
		file.getModule().getInvoker().execute(new CommandDownload(this.file));
	}
	
	/**
	 * Handling of new state
	 */
	public boolean handle() {
		//TODO implement download state handling
		//setProgress(getProgress()+1);
		if(getProgress() == 100){
			setProgress(getProgress()+1);
		}
		else if(getProgress() > 100){
			AppStarter l = new AppStarter(file.getFileAsObject().getPath());
			if(l.launch()){
				StateWaiting nState = new StateWaiting(iterator, file);
				file.setCurrentState(nState);
			}
			else{
				StateError nState = new StateError(iterator, file);
				nState.setup("CANNOT START EXTERNAL APPLICATION");
				file.setCurrentState(nState);
			}
		}
		return false;
	}

}
